package com.hotel.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotel.common.Result;
import com.hotel.dto.MemberDTO;
import com.hotel.vo.MemberVO;
import com.hotel.service.MemberService;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 会员管理控制器
 */
@RestController
@RequestMapping("/member")
@Validated
public class MemberController {
    
    @Autowired
    private MemberService memberService;
    
    /**
     * 分页查询会员列表
     */
    @GetMapping("/list")
    public Result<Page<MemberVO>> getMemberList(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String level,
            @RequestParam(required = false) Integer status) {
        
        Page<MemberVO> page = memberService.getMemberPage(current, size, keyword, level, status);
        return Result.success(page);
    }
    
    /**
     * 根据ID获取会员详情
     */
    @GetMapping("/{id}")
    public Result<MemberVO> getMemberById(@PathVariable @NotNull Long id) {
        MemberVO member = memberService.getMemberById(id);
        if (member == null) {
            return Result.error("会员不存在");
        }
        return Result.success(member);
    }
    
    /**
     * 创建会员
     */
    @PostMapping
    public Result<String> createMember(@RequestBody @Valid MemberDTO memberDTO) {
        // 检查手机号是否已存在
        if (memberService.getMemberByPhone(memberDTO.getPhone()) != null) {
            return Result.error("手机号已存在");
        }
        
        boolean success = memberService.createMember(memberDTO);
        if (success) {
            return Result.success("会员创建成功");
        } else {
            return Result.error("会员创建失败");
        }
    }
    
    /**
     * 更新会员信息
     */
    @PutMapping("/{id}")
    public Result<String> updateMember(@PathVariable @NotNull Long id, 
                                      @RequestBody @Valid MemberDTO memberDTO) {
        boolean success = memberService.updateMember(id, memberDTO);
        if (success) {
            return Result.success("会员信息更新成功");
        } else {
            return Result.error("会员信息更新失败");
        }
    }
    
    /**
     * 删除会员
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteMember(@PathVariable @NotNull Long id) {
        boolean success = memberService.deleteMember(id);
        if (success) {
            return Result.success("会员删除成功");
        } else {
            return Result.error("会员删除失败");
        }
    }
    
    /**
     * 根据手机号查询会员
     */
    @GetMapping("/phone/{phone}")
    public Result<MemberVO> getMemberByPhone(@PathVariable @NotEmpty String phone) {
        var member = memberService.getMemberByPhone(phone);
        if (member == null) {
            return Result.error("会员不存在");
        }
        
        MemberVO vo = memberService.getMemberById(member.getId());
        return Result.success(vo);
    }
    
    /**
     * 根据会员号查询会员
     */
    @GetMapping("/memberNo/{memberNo}")
    public Result<MemberVO> getMemberByMemberNo(@PathVariable @NotEmpty String memberNo) {
        var member = memberService.getMemberByMemberNo(memberNo);
        if (member == null) {
            return Result.error("会员不存在");
        }
        
        MemberVO vo = memberService.getMemberById(member.getId());
        return Result.success(vo);
    }
    
    /**
     * 更新会员积分
     */
    @PostMapping("/{id}/points")
    public Result<String> updateMemberPoints(
            @PathVariable @NotNull Long id,
            @RequestParam @NotNull Integer points,
            @RequestParam(required = false) String source,
            @RequestParam(required = false) String description) {
        
        boolean success = memberService.updateMemberPoints(id, points, source, description);
        if (success) {
            return Result.success("积分更新成功");
        } else {
            return Result.error("积分更新失败");
        }
    }
    
    /**
     * 升级会员等级
     */
    @PostMapping("/{id}/upgrade")
    public Result<String> upgradeMemberLevel(
            @PathVariable @NotNull Long id,
            @RequestParam @NotEmpty String newLevel) {
        
        boolean success = memberService.upgradeMemberLevel(id, newLevel);
        if (success) {
            return Result.success("会员等级升级成功");
        } else {
            return Result.error("会员等级升级失败");
        }
    }
    
    /**
     * 更新会员状态（冻结/解冻）
     */
    @PostMapping("/{id}/status")
    public Result<String> updateMemberStatus(
            @PathVariable @NotNull Long id,
            @RequestParam @NotNull Integer status) {
        
        boolean success = memberService.updateMemberStatus(id, status);
        if (success) {
            String message = status == 1 ? "会员账户已解冻" : "会员账户已冻结";
            return Result.success(message);
        } else {
            return Result.error("状态更新失败");
        }
    }
    
    /**
     * 获取会员统计数据
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getMemberStats() {
        Map<String, Object> stats = memberService.getMemberStats();
        return Result.success(stats);
    }
    
    /**
     * 获取会员等级分布
     */
    @GetMapping("/level-distribution")
    public Result<List<Map<String, Object>>> getMemberLevelDistribution() {
        List<Map<String, Object>> distribution = memberService.getMemberLevelDistribution();
        return Result.success(distribution);
    }
    
    /**
     * 获取会员增长趋势
     */
    @GetMapping("/growth-trend")
    public Result<List<Map<String, Object>>> getMemberGrowthTrend(
            @RequestParam(defaultValue = "month") String type) {
        
        List<Map<String, Object>> trend = memberService.getMemberGrowthTrend(type);
        return Result.success(trend);
    }
    
    /**
     * 批量操作会员
     */
    @PostMapping("/batch")
    public Result<String> batchOperation(
            @RequestParam @NotEmpty List<Long> memberIds,
            @RequestParam @NotEmpty String operation,
            @RequestParam(required = false) Object params) {
        
        boolean success = memberService.batchOperation(memberIds, operation, params);
        if (success) {
            return Result.success("批量操作成功");
        } else {
            return Result.error("批量操作失败");
        }
    }
    
    /**
     * 导出会员数据
     */
    @GetMapping("/export")
    public Result<String> exportMemberData(
            @RequestParam(required = false) String level,
            @RequestParam(required = false) Integer status) {
        
        try {
            memberService.exportMemberData(level, status);
            return Result.success("数据导出成功");
        } catch (Exception e) {
            return Result.error("数据导出失败: " + e.getMessage());
        }
    }
}